<template>
  <CDialog
    class="connect-factory-dialog"
    :title="title"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
    :loading="loading"
    size="small"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-position="top">
      <el-row :gutter="20">
        <!-- 规则类别 -->
        <el-col :span="24">
          <el-form-item label="规则类别" prop="category">
            <CSelect v-model="formData.category" placeholder="请选择" :disabled="isEdit">
              <el-option
                v-for="item in MaterialsClassificationOptions"
                :value="item.value"
                :key="item.value"
              >
                <div class="g-flex-between-center">
                  <span class="g-mr10">{{ item.label }}</span>
                  <span class="g-font-12n4">{{ item.subTitle }}</span>
                </div>
              </el-option>
            </CSelect>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="适用标准" prop="applicableStandard">
            <CSelect
              v-model="formData.applicableStandard"
              placeholder="请选择"
              multiple
              :disabled="isEdit"
            >
              <el-option
                v-for="item in StandardOptions"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              >
              </el-option>
            </CSelect>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="规则KEY" prop="keyName">
            <el-input v-model.trim="formData.keyName" placeholder="请输入" :disabled="isEdit" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="规则因子" prop="factorNo" class="factor">
            <template #label>
              <span>规则因子</span>
              <el-button
                text
                type="primary"
                @click="relationFactorVisible = true"
                class="relation-factor-button"
                >关联因子</el-button
              >
            </template>
            <el-input v-model="formData.factorName" placeholder="请选择" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <CFootprintFactorDrawer v-model:visible="relationFactorVisible" @finish="handleFinish" />
  </CDialog>
</template>
<script lang="ts">
export default {
  name: 'HandleRuleDialog'
};
</script>
<script lang="ts" setup>
import { defineProps, withDefaults, defineEmits, computed, ref, watch, reactive } from 'vue';
import { useMessage } from '@/hooks/useMessage';
import { rules } from './rules';
import { IGetFactorMatchListRes } from '@/apis/system/config/model/factorMatchingRule';
import { MaterialsClassificationOptions } from '@/constants/system';
import { CDialog } from '@/components/CDialog';
import { CSelect } from '@/components/CSelect';
import { StandardOptions } from '@/constants/pcf';
import { updateRule, addRule } from '@/apis/system/config/factorMatchingRule';
import CFootprintFactorDrawer from '@/businessComponents/CFootprintFactorDrawer/index.vue';

interface IPropsType {
  visible: boolean;
  currentRule?: IGetFactorMatchListRes;
}
const props = withDefaults(defineProps<IPropsType>(), {
  visible: false
});
const emit = defineEmits(['update:visible', 'refresh']);

const { createMessage } = useMessage();

const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emit('update:visible', val);
  }
});
watch(
  () => dialogVisible.value,
  visible => {
    initVisible();
  }
);

const formRef = ref();
const loading = ref(false);
const relationFactorVisible = ref(false);
const formData = reactive({
  category: '',
  applicableStandard: [] as string[],
  keyName: '',
  factorNo: '',
  factorName: ''
});

const handleFinish = (selectedFactor: any) => {
  formData.factorNo = selectedFactor.factorNo;
  formData.factorName = selectedFactor.factorName;
};

// 提交按钮
function handleConfirm() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      submitTaskReq();
    }
  });
}

// 请求接口
async function submitTaskReq() {
  try {
    loading.value = true;
    if (isEdit.value) {
      const params = {
        ruleNo: props.currentRule?.ruleNo as string,
        factorNo: formData.factorNo
      };
      await updateRule(params);
      createMessage.success('编辑成功！');
    } else {
      const params = {
        category: formData.category,
        applicableStandard: formData.applicableStandard,
        keyName: formData.keyName,
        factorNo: formData.factorNo
      };
      await addRule(params);
      createMessage.success('新增成功！');
    }
    dialogVisible.value = false;
    loading.value = false;
    emit('refresh');
  } catch (error) {
    loading.value = false;
  }
}

// 打开时初始化
async function initVisible() {
  if (isEdit.value) {
    formData.category = props.currentRule?.category || '';
    formData.applicableStandard = props.currentRule?.applicableStandard || [];
    formData.keyName = props.currentRule?.keyName || '';
    formData.factorNo = props.currentRule?.factorNo || '';
    formData.factorName = props.currentRule?.factorName || '';
  } else {
    formData.category = '';
    formData.applicableStandard = [] as string[];
    formData.keyName = '';
    formData.factorNo = '';
    formData.factorName = '';
    formRef.value?.resetFields();
  }
}

const title = computed(() => {
  return `${props.currentRule?.ruleNo ? '编辑' : '新增'}规则`;
});
const isEdit = computed(() => {
  return props.currentRule?.ruleNo ? true : false;
});
</script>

<style lang="scss" scoped>
.factor {
  :deep(.el-form-item__label) {
    position: relative !important;
    width: 100%;

    .relation-factor-button {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }
}
</style>
